/*
 * @ProjectName: 编程学习
 * @Copyright:   2019 HangZhou Yi Dev, Ltd. All Right Reserved.
 * @address:     https://yiyuery.github.io/
 * @date:        2019/5/20 20:57
 * @email:       xiazhaoyang@live.com
 * @description: 本内容仅限于编程技术学习使用，转发请注明出处.
 */
package com.example.swagger.common.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Yi
 * @version v1.0.0
 * @date 2019-06-08 15:45
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify By: {修改人} 2019-06-08
 * @modify reason: {方法名}:{原因}
 * ...
 */
public class PDFHelper {

    /**
     * 添加图片到PDF
     * @param document
     * @param imagePath
     * @throws IOException
     */
    public static void addImageToPDF(PDDocument document, String imagePath)
            throws IOException
    {
        InputStream in = new FileInputStream(imagePath);
        BufferedImage img = ImageIO.read(in);
        float width = img.getWidth();
        float height = img.getHeight();
        PDPage page = new PDPage(new PDRectangle(width, height));
        document.addPage(page);
        PDImageXObject imgObj =PDImageXObject.createFromFile(imagePath, document);
        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.drawImage(imgObj, 0, 0);
        contentStream.close();
        in.close();
    }


    /**
     * 图片转PDF
     * @param images
     * @param outPutPath
     * @throws IOException
     */
    public static void createPDFFromImage(List<String> images,String outPutPath) throws IOException {
        File output = Paths.get(outPutPath).toFile();
        TransformHelper.initFile(output);
        PDDocument document = new PDDocument();
        images.forEach(imagePath->{
            try {
                addImageToPDF(document,imagePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        document.save(outPutPath);
        document.close();
    }
}
